package com.xiang.sql.service;

import jakarta.annotation.Resource;

import java.util.concurrent.CompletableFuture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiang.api.Util;
import com.xiang.api.service.WxService;
import com.xiang.sql.entity.Task;
import com.xiang.sql.mapper.TaskMapper;

/**
 * 定时任务 服务实现类
 * 
 * @author mac-xiang
 */
@Service
public class TaskService extends ServiceImpl<TaskMapper, Task> {
  @Resource
  TaskMapper mapper;

  public void create(String type, long time, String content) {
    Task entity = new Task();
    entity.type = type;
    entity.time = time;
    entity.content = content;
    mapper.insert(entity);
  }

  @Autowired
  WxService wxService;

  private void run(QueryWrapper<Task> q) {
    mapper.selectList(q.clone()).forEach(e -> {
      switch (e.type) {
        case "发货":
          wxService.delivery(e.content);
          break;

        default:
          break;
      }
    });
  }

  public void run() {
    QueryWrapper<Task> q = new QueryWrapper<Task>().le("time", Util.time());
    CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
      run(q);
    });
    mapper.delete(q.clone().gt("time", 0));
    f.join();
  }
}
